package com.lk.web.controller;

import com.lk.base.result.Result;
import com.lk.web.entity.SysPermission;
import com.lk.web.service.SysPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: lk-security-parent
 * @description: 权限管理
 * @author: Aspirin
 * @create: 2020-06-14 22:58
 */
@Controller
@RequestMapping("/permission")
public class SysPermissionController {
  private static final Logger logger = LoggerFactory.getLogger(SysPermissionController.class);
  private static final String HTML_PREFIX = "system/permission/";
  @Autowired SysPermissionService sysPermissionService;

  /** 跳转权限管理页面 */
  @PreAuthorize("hasAuthority('sys:permission')")
  @GetMapping(value = {"/", ""})
  public String permission() {
    return HTML_PREFIX + "permission-list";
  }

  /** 权限列表 */
  @PreAuthorize("hasAuthority('sys:permission:list')")
  @PostMapping("/list")
  @ResponseBody
  public Result list() {
    List<SysPermission> list = sysPermissionService.list();
    return Result.ok(list);
  }

  /**
   * 跳转新增或者修改页面 /form 新增; /form/{id} 修改 @PathVariable(required = false) 设置为false，则id可传也可不传，不然报500
   */
  @PreAuthorize("hasAnyAuthority('sys:permission:edit', 'sys:permission:add')")
  @GetMapping(value = {"/form", "/form/{id}"})
  public String form(@PathVariable(required = false) Long id, Model model) { // Map<String,Object>
    // 1. 通过权限id查询对应权限信息
    SysPermission permission = sysPermissionService.getById(id);
    // 绑定后页面可获取
    model.addAttribute("permission", permission == null ? new SysPermission() : permission);
    return HTML_PREFIX + "permission-form";
  }

  /**
   * 提交新增或修改的数据,修改put，新增post
   *
   * @param permission 权限实体
   */
  @PreAuthorize("hasAnyAuthority('sys:permission:edit', 'sys:permission:add')")
  @RequestMapping(
      value = "",
      method = {RequestMethod.PUT, RequestMethod.POST})
  public String saveOrUpdate(SysPermission permission) {
    sysPermissionService.saveOrUpdate(permission);
    return "redirect:/permission";
  }

  /**
   * 删除权限
   *
   * @param id 权限id
   */
  @PreAuthorize("hasAuthority('sys:permission:delete')")
  @DeleteMapping("/{id}")
  @ResponseBody
  public Result deleteById(@PathVariable("id") Long id) {
    sysPermissionService.deleteById(id);
    return Result.ok();
  }
}
